﻿using UnityEngine;
using UnityEngine.Helper;
using UnityEngine.UI;
using UnityEngine.UI.Packing;

namespace UnityEditor.UI
{
    [CustomEditor(typeof(PackingImage))]
    public class PackingImageEditor : ImageEditor
    {
        private Sprite lastTexture = null;
        private DynamicAtlasPreviewGUI _previewGUI;
        protected override void OnEnable()
        {
            base.OnEnable();
            _previewGUI = new DynamicAtlasPreviewGUI((target as PackingImage).mainTexture as Texture2D);
            _previewGUI.OnEnable();
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            PackingImage image = (PackingImage)target;
            GUILayout.Space(5);
            EditorGUILayout.LabelField("PackingImge");
            GUILayout.Space(5);
            image.mGroup = (DynamicAtlasGroup)EditorGUILayout.EnumPopup("Group", image.mGroup);
            image.mAndroidTextureFormat = (TextureFormat)EditorGUILayout.EnumPopup("Android TextureFormat", image.mAndroidTextureFormat);
            image.mIosTextureFormat = (TextureFormat)EditorGUILayout.EnumPopup("IOS TextureFormat", image.mIosTextureFormat);
            //EditorGUILayout.LabelField("Texture Path", myScript.currentPath);

            GUILayout.Space(5);


            if (EditorApplication.isPlaying)
            {
                _previewGUI.OnInspectorGUI(image.mGroup);            }
            else
            {
                if ((lastTexture != image.sprite) || (image.sprite != null && image.currentPath == null))
                {
                    lastTexture = image.sprite;
                    string path = PathUtil.RemoveResourcePath(AssetDatabase.GetAssetPath(image.sprite));
                    image.currentPath = path;
                }

                if (image.sprite == null)
                {
                    lastTexture = null;
                    image.currentPath = null;
                }
            }
        }

        public override void OnPreviewGUI(Rect rect, GUIStyle background)
        {
            _previewGUI.OnPreviewGUI(base.OnPreviewGUI,rect,background,(target as PackingImage).canvasRenderer.GetColor());
        }
    }
}
